import { loginUseUsernameAndPassword, getUserLabBuInfo } from '../models/gpo-api.js'
import jsonwebtoken from 'jsonwebtoken'
import { z } from 'zod'
import { OpenAPIRegistry, extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'

extendZodWithOpenApi(z)

export const registryAuth = new OpenAPIRegistry()

const loginSchema = z.object({
  username: z.string().openapi({ description: 'The username of the user.', example: 'apac\\User_Name' }),
  password: z.string().openapi({ description: 'The password of the user.', example: 'securePassword' })
}).openapi({ summary: 'User authentication', description: 'Authenticates the user using a username and password, returning a JWT and SGS token upon success.' })

const loginResponseSchema = z.object({
  success: z.boolean().openapi({ description: 'Indicates if authentication was successful.', example: true }),
  uname: z.string().openapi({ description: 'The username of the authenticated user.', example: 'User_Name' }),
  token: z.string().openapi({ description: 'The JWT token.' }),
  sgsToken: z.string().openapi({ description: 'The SGS token.' }),
  role: z.string().openapi({ description: 'The user role.', example: 'user' }),
  userInfo: z.object({}).passthrough().openapi({ description: 'Complete user information from GPO API.' })
}).openapi({ description: 'Authentication successful, returns tokens and user info.' })

registryAuth.registerPath({
  method: 'post',
  path: '/auth/login',
  description: 'Authenticates the user using a username and password, returning a JWT and SGS token upon success.',
  summary: 'User authentication',
  request: {
    body: {
      description: 'The username and password of the user.',
      content: {
        'application/json': {
          schema: loginSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: 'Authentication successful, returns tokens.',
      content: {
        'application/json': {
          schema: loginResponseSchema
        }
      }
    },
    401: {
      description: 'Unauthorized, username or password incorrect.'
    }
  }
})

export const userAuth = async (ctx) => {
  try {
    const { username, password } = ctx.request.body
    console.log('Login attempt for username:', username)
    
    const { sgsToken, username: uname } = await loginUseUsernameAndPassword(username, password)
    
    console.log('Login successful for:', uname)
    // console.log('SGS Token:', sgsToken)
    
    if (sgsToken) {
      // 获取用户的Lab和BU信息（完整的用户信息）
      console.log('=== 开始获取用户Lab和BU信息 ===')
      console.log('sgsToken:', sgsToken ? '已提供' : '未提供')
      
      let userInfo = null
      try {
        userInfo = await getUserLabBuInfo(sgsToken)
        console.log('getUserLabBuInfo API原始响应:', userInfo)
        
        if (!userInfo) {
          console.warn('getUserLabBuInfo返回null，尝试重新调用...')
          // 等待一小段时间后重试
          await new Promise(resolve => setTimeout(resolve, 500))
          userInfo = await getUserLabBuInfo(sgsToken)
          console.log('getUserLabBuInfo重试响应:', userInfo)
        }
        
        if (userInfo) {
          console.log('✓ 成功获取用户信息:', {
            locationName: userInfo.locationName,
            locationCode: userInfo.locationCode,
            labCode: userInfo.labCode,
            labName: userInfo.labName
          })
        } else {
          console.error('❌ 无法获取用户Lab和BU信息')
        }
      } catch (error) {
        console.error('获取用户Lab和BU信息时发生异常:', error)
        userInfo = null
      }
      
      // 添加用户名到响应数据中
      if (userInfo) {
        userInfo.username = uname
      }
      
      // 根据用户名或其他条件确定用户角色
      const role = determineUserRole(uname, userInfo)
      console.log('Determined role for', uname, ':', role)
      
      console.log('=== 准备生成JWT token ===')
      console.log('Token将包含的locationName:', userInfo?.locationName || 'null')
      
      const token = jsonwebtoken.sign({ 
        sgsToken, 
        uname, 
        email: userInfo?.email, 
        role,
        locationName: userInfo?.locationName,
        locationCode: userInfo?.locationCode,
        labCode: userInfo?.labCode,
        labName: userInfo?.labName
      }, process.env.JWT_SEED, { expiresIn: '4h' })
      
      console.log('✓ JWT token生成成功，包含locationName:', userInfo?.locationName || 'null')
      ctx.body = {
        success: true,
        uname,
        token,
        sgsToken,
        role,
        userInfo: userInfo  // 返回完整的getUserLabBuInfo响应信息
      }
    } else {
      ctx.status = 401
      ctx.body = {
        success: false,
        info: '登陆失败，用户名或密码错误'
      }
    }
  } catch (error) {
    console.error('Login error:', error)
    ctx.status = 401
    ctx.body = {
      success: false,
      info: '登陆失败，用户名或密码错误'
    }
  }
}

import fs from 'fs'
import path from 'path'

// 读取用户权限配置
const getUserPermissions = () => {
  try {
    const permissionsPath = path.join(process.cwd(), 'server', 'data', 'user-permissions.json')
    const data = fs.readFileSync(permissionsPath, 'utf8')
    return JSON.parse(data)
  } catch (error) {
    console.error('读取用户权限配置失败:', error)
    // 返回默认配置
    return {
      systemAdmins: ['admin', 'administrator', 'sgs_admin', 'apac\\Glenn_Gao', 'Glenn_Gao'],
      regularAdmins: [],
      users: []
    }
  }
}

// 确定用户角色的函数
export const determineUserRole = (username, userInfo) => {
  // 这里可以根据实际业务逻辑来判断用户角色
  // 例如：根据用户名、部门、权限组等信息
  
  // console.log('Checking role for username:', username)
  
  // 从文件读取权限配置
  const permissions = getUserPermissions()
  const systemAdminUsers = permissions.systemAdmins || []
  const adminUsers = permissions.regularAdmins || []
  
  // console.log('System admin users list:', systemAdminUsers)
  // console.log('Regular admin users list:', adminUsers)
  
  const isSystemAdmin = systemAdminUsers.some(systemUser => {
    const match = username.toLowerCase() === systemUser.toLowerCase()
    return match
  })
  
  const isRegularAdmin = adminUsers.some(adminUser => {
    const match = username.toLowerCase() === adminUser.toLowerCase()
    return match
  })
  
  // 也可以根据userInfo中的其他字段判断
  // 例如：userInfo.department, userInfo.role, userInfo.permissions等
  
  if (isSystemAdmin) {
    return 'system'
  } else if (isRegularAdmin) {
    return 'admin'
  } else {
    return 'user'
  }
}